import './index.less'
import { useEffect, useState } from 'react'
import DanmuMessage from './DanmuMessage'
import eventbus from '../../../services/eventbus'
import ioService from '../../../services/ioService'
import DanmuUnit from '../DanmuUnit'

export default () => {
    const [messages, setMessages] = useState<DanmuMessage[]>([])

    function onMessage({ message }) {
        setMessages(messages => [...messages,
            new DanmuMessage(message)])
    }

    function onSelfMessage(message: string) {
        setMessages(messages => [...messages,
            new DanmuMessage(message, true)])
    }

    useEffect(() => {
        ioService.on('message', onMessage)
        eventbus.on('selfMessage', onSelfMessage)
        return () => {
            ioService.off('message', onMessage)
            eventbus.off('selfMessage', onSelfMessage)
        }
    }, [])

    return <div className="danmu-container">
        {messages.map((item, index) =>
            <DanmuUnit danmu={item} key={index} />)}
    </div>

}